package _8nio;


import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description:
 * @author: wang zhen
 * @create: 2022-07-11 11:05
 */
public class FileChannelTest {


    @Test
    public void test1() {

        String data="你好hello123456";
        FileOutputStream fileOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream("C:\\Users\\test\\Desktop\\a.txt");

            FileChannel channel = fileOutputStream.getChannel();


            ByteBuffer buffer = ByteBuffer.allocate(data.getBytes().length);
            buffer.put(data.getBytes());

            buffer.flip();
            channel.write(buffer);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            try {
                if(fileOutputStream!=null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }


    @Test
    public void test2() {

        FileInputStream fileInputStream=null;
        try {
            fileInputStream=new FileInputStream("C:\\Users\\test\\Desktop\\a.txt");

            FileChannel channel = fileInputStream.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(6);

            while (channel.read(buffer)!=-1){


                System.out.println(new String(buffer.array(),0,buffer.position(),"UTF-8"));
                buffer.clear();
            }


        } catch (Exception e) {
            e.printStackTrace();

        } finally {

            try {
                if(fileInputStream!=null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}
